/**
 * @author banglong
 * @date 2016/9/12.
 */
define(['Layer', 'text!../html/index/goodsQuery/goodsQueryTemp.html!strip', 'layPage', 'rootPath', 'avalon', 'tools',
    'Condition', 'conditionsUtils', 'newBillApi'
  ],
  function (layer, htmlTemp, laypage, rootPath, avalon, tools,
    Condition, conditionsUtils, api) {

    // 设定路径
    laypage.dir = rootPath.getRootPath() + 'js/common/laypage/skin/laypage.css';

    return function () {

      var self = this;
      var runtimeParam;
      var getRuntimeParma = function () {
        return {
          timeObj: {},
          imgHtmlTemp: '<div id="showGoodsImg" class="showGoodsImg"><img src="" alt=""/></div>'
        };
      };

      var goodsQueryVm;
      var getVmOption = function () {
        return {
          $id: 'goodsSelect',
          breadcrumb: '',
          searchInput: '',

          goods: [],
          size: 30, // 大小
          pages: 0, // 页数
          count: 0, // 总数
          currentPages: 0, // 当前页码

          showFreshIcon: true,
          showAllGoods: false,

          back: function () {
            tools.removeFirstChildNode(document.querySelector('#main'), documentNodeTree);
            runtimeParam.checkBreadcrumb();
            runtimeParam.showMenu();
            self.destroy();
          },
          handleInputSearch: function () {
        	 
            tools.throttle(runtimeParam.timeObj, function () {
              getAllGoods(runtimeParam);
            });
          },
          handleMouseenter: function (event, index) {
            if (!runtimeParam.showGoodsImg) {
              runtimeParam.showGoodsImg = $('#showGoodsImg');
            }
            var goods = goodsQueryVm.goods[index];
            tools.throttle(runtimeParam.timeObj, function () {
              // 需要查询物品的地址信息
              api.getImages({
                  className: 'ImageManager',
                  method: 'getImages',
                  imgType: '6',
                  goodsType: 1,
                  folder: goods.GoodsCode
                })
                .then(function (data) {
                  if (data.issuccess === 0) {
                    var result = JSON.parse(data.result);
                    if (result.length > 0) {
                      // 显示图片幻灯片
                      tools.showImgDialog(result)();
                    }
                  }
                });
            });
          },
          handleMouseout: function (event, index) {
            tools.throttle(runtimeParam.timeObj, function () {
              runtimeParam.showGoodsImg.hide();
            });
          }
        };
      };

      function hideRefreshIcon() {
        layer.close(runtimeParam.loadingIndex); // 隐藏刷新圈
        goodsQueryVm.showFreshIcon = false;
      }

      function getAllGoods(runtimeParam) {
        runtimeParam.loadingIndex = layer.load();

        var GoodsBookIDs = '';
        runtimeParam.Openparm.GoodsBook.split(',').forEach(function (id, index, arr) {
          if (index !== arr.length - 1) {
            GoodsBookIDs += "'" + id + "',";
          } else {
            GoodsBookIDs += "'" + id + "'";
          }
        });

        var condition = conditionsUtils.getGoodsCondition({
          IsOpen: true,
          //IsImmediatelyUse: !runtimeParam.isProviderDept,
          GoodsBookID: GoodsBookIDs,
          searchValue: goodsQueryVm.searchInput,
          isProviderDept: true,
          isGetAll: true
        });

        api.getGoodsToDataSet({
          className: 'GoodsManager',
          method: 'GetGoodsToDataSetForWeb',
          condition: JSON.stringify(condition),
          nowPage: runtimeParam.nowPage || 1,
          pageSize: goodsQueryVm.size || 10
        }).then(function (jsonResult) {

          if (jsonResult.issuccess !== 0) {
            return Promise.reject("系统错误，请联系管理员！");
          }

          initGoodsArray(jsonResult);
          hideRefreshIcon();

        })['catch'](function (ex) {
          hideRefreshIcon();
          tools.handleError(ex);
        });
      }

      function initGoodsArray(jsonResult) {
        var result = JSON.parse(jsonResult.result);
        var goods = result.pageContent.concat();

        // todo 当前科室是否可领
        goods.forEach(function (data) {
          data.canUse = true;
        });
        goodsQueryVm.pages = Math.ceil(result.pageCount / result.pageSize);
        goodsQueryVm.count = result.pageCount;
        goodsQueryVm.currentPages = result.nowPage;
        result = null;

        // 设置分页
        initPage(goodsQueryVm, goods);
      }

      var initPage = function (goodsSelectVm, goods) {
        var page = document.querySelector('#goodsselectpage');
        page.html = '';
        laypage({
          cont: page,
          curr: goodsSelectVm.currentPages,
          pages: goodsSelectVm.pages,
          jump: function (obj, first) {

            goodsSelectVm.goods.splice(0, goodsSelectVm.goods.length);
            goodsSelectVm.chooseIndex = 0;
            goodsSelectVm.goods.pushArray(goods);

            if (!first) {
              //得到了当前页，用于向服务端请求对应数据
              runtimeParam.nowPage = obj.curr;
              getAllGoods(runtimeParam);
            }
          }
        });
        hideRefreshIcon();
      };

      this.init = function ($main, param) {
    	 
        runtimeParam = getRuntimeParma();
        runtimeParam = Object.assign(runtimeParam, param);

        $main.append(htmlTemp);
        goodsQueryVm = tools.initAvalonVm(avalon, getVmOption(), ".goods-select");

        goodsQueryVm.showAllGoods = param.showAllGoods;
        goodsQueryVm.breadcrumb = param.breadcrumb;
        goodsQueryVm.showFreshIcon = true;

        document.querySelector('#goodsselectpage').innerHTML = '';
        getAllGoods(runtimeParam);
        if (!document.querySelector("#showGoodsImg")) {
          $(document.body).append(runtimeParam.imgHtmlTemp);
        }
        tools.bindDestroyMethod(self.destroy);
      };

      this.destroy = function () {
        runtimeParam = null;
        goodsQueryVm = null;
        if (document.querySelector("#showGoodsImg")) {
          document.body.removeChild(document.querySelector('#showGoodsImg'))
        }
        tools.destroy(getVmOption());
      };
    };
  });